package com.stanwind.sgit;

import com.stanwind.sgit.exception.GitException;
import com.stanwind.sgit.exec.GitLog;
import com.stanwind.sgit.exec.GitPull;
import com.stanwind.sgit.exec.GitRemote;
import com.stanwind.sgit.util.StringUtils;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ShellGit
 *
 * @author : Stan
 * @version : 1.0
 * @date :  2019-11-29 16:19
 **/
public class ShellGit {
    public static final Logger logger = LoggerFactory.getLogger(ShellGit.class);

    public static boolean checkAndPull(File localRepo) throws GitException {
        final GitRemote gitRemote = new GitRemote();
        final GitLog gitLogLocal = new GitLog();
        final GitLog gitLogRemote = new GitLog();
        final GitPull gitPull = new GitPull();

        gitRemote.exec(localRepo);
        String remoteUrl = gitRemote.getRemote();
        logger.info("获取到中心仓地址: {}", remoteUrl);
        File remoteRepo = new File(remoteUrl);

        gitLogLocal.exec(localRepo);
        String localHash = gitLogLocal.getLatestHash();
        logger.info("本地最新sha: "  + localHash);

        gitLogRemote.exec(remoteRepo);
        String remoteHash = gitLogRemote.getLatestHash();
        logger.info("远程最新sha: " + remoteHash);

        if (StringUtils.isNotBlank(remoteHash) && localHash != null) {
            if (!remoteHash.equals(localHash)) {
                logger.info("sha不一致，进行pull");
                gitPull.exec(localRepo);
            } else {
                logger.info("sha一致, 不操作");
            }
        } else {
            throw new GitException("获取Git仓库数据异常");
        }

        return true;
    }

    public static void main(String[] args) throws GitException {
        File localRepo = new File("F:\\gittest\\B\\Base");
        checkAndPull(localRepo);
    }
}
